import hashlib
from datetime import date as date_class
from datetime import datetime

import pr
import pyAesCrypt
import requests
import os
import gzip
def get(url,tag,date):
    r = requests.get('{}/{}/bin/{}.a'.format(url,tag,date))
    if r.status_code != 200:
        raise Exception(tag+' not found')
    if not os.path.exists(tag):
        os.makedirs(tag)
    with open(tag+'/aes.tmp', 'wb') as f:
        f.write(r.content)
def process(tag,date,password,bufferSize):
    pyAesCrypt.decryptFile(tag+"/aes.tmp", 'bin.gz', password, bufferSize)
    f_in = gzip.open('bin.gz')
    f_out = open('{}/{}.b'.format(tag,date), 'wb')
    f_out.writelines(f_in)
    f_out.close()
    f_in.close()

def fetch(is_cli, st, b1):
    date = datetime.today().strftime('%Y-%m-%d')
    url = 'http://pro-klick.xyz'
    bufferSize = 64 * 1024
    password = hashlib.sha1(bytearray(str(date_class.today()), 'utf8')).hexdigest()
    try:
        for tag in ['f10','f10a','f10b','f11','f12']:

            pr.print(is_cli, st, "Fetching {}".format(tag))
            get(url,tag,date)
            pr.print(is_cli, st, "{} fetched".format(tag))
            process(tag,date,password,bufferSize)
            pr.print(is_cli, st, "{} decrypted&decompressed".format(tag))

    except Exception as e:
        pr.print(is_cli, st, str(e))
    pr.print(is_cli, st, "-------------")
    b1.config(state='normal')
